import { ref } from 'vue'
import http from '@/support/http'
import type { TaskRow, CatchTableInstance } from '../types'
import { FILE_STATE, TASK_STATE } from '../constants'

/**
 * 状态更新 Composable
 * 用于统一管理总表状态和任务状态的更新逻辑
 */
export function useStatusUpdate(catchTableRef: { value: CatchTableInstance | null }) {
	/**
	 * 更新总表状态
	 * 遍历当前列表数据，只对总表状态为"导入中"的数据进行查询
	 */
	async function updateSourceFileStatus() {
		if (!catchTableRef.value) {
			return
		}

		const tableData = catchTableRef.value.tableData || []
		if (!tableData || tableData.length === 0) {
			return
		}

		// 收集需要查询的数据
		const queryTasks: Array<{ row: TaskRow; sourceFileId: number }> = []

		tableData.forEach((row) => {
			if (
				row.source_file?.id &&
				(row.source_file_state === FILE_STATE.IMPORTING || row.source_file_state === FILE_STATE.PENDING)
			) {
				queryTasks.push({
					row,
					sourceFileId: row.source_file_id
				})
			}
		})

		if (queryTasks.length === 0) {
			return
		}

		try {
			// 并发请求所有需要更新的数据
			const requestPromises = queryTasks.map(async ({ row, sourceFileId }) => {
				const response = await http.get('/dc/sourceFile/detail', {
					id: sourceFileId
				})

				if (response.data.code !== 10000 || !response.data.data) {
					throw new Error(`接口返回失败 (ID: ${sourceFileId})`)
				}

				return {
					row,
					sourceFileData: response.data.data
				}
			})

			const results = await Promise.all(requestPromises)

			// 统一更新状态
			results.forEach(({ row, sourceFileData }) => {
				if (row.source_file) {
					row.source_file_state = sourceFileData.file_state
					if (sourceFileData.source_file_original_name) {
						row.source_file_original_name = sourceFileData.file_name
					}
					if (sourceFileData.remark) {
						row.source_file_remark = sourceFileData.remark
					}
				}
			})
		} catch (error) {
			console.error('更新总表状态失败:', error)
			throw error
		}
	}

	/**
	 * 更新任务状态
	 * 遍历当前列表数据，只对任务状态为"核对中"的数据进行查询
	 */
	async function updateTaskStatus() {
		if (!catchTableRef.value) {
			return
		}

		const tableData = catchTableRef.value.tableData || []
		if (!tableData || tableData.length === 0) {
			return
		}

		// 收集需要查询的数据
		const queryTasks: Array<{ row: TaskRow; taskId: number }> = []

		tableData.forEach((row) => {
			if (
				row.task_id &&
				(row.task_state === TASK_STATE.QUEUING || row.task_state === TASK_STATE.CHECKING) &&
				row.source_file?.file_state === FILE_STATE.SUCCESS
			) {
				queryTasks.push({
					row,
					taskId: row.task_id
				})
			}
		})

		if (queryTasks.length === 0) {
			return
		}

		try {
			// 并发请求所有需要更新的数据
			const requestPromises = queryTasks.map(async ({ row, taskId }) => {
				const response = await http.get('/dc/check/process', {
					task_id: taskId
				})

				if (response.data.code !== 10000 || !response.data.data) {
					throw new Error(`接口返回失败 (Task ID: ${taskId})`)
				}

				return {
					row,
					taskData: response.data.data
				}
			})

			const results = await Promise.all(requestPromises)

			// 统一更新状态
			results.forEach(({ row, taskData }) => {
				if (taskData.task_state !== undefined) {
					row.task_state = taskData.task_state
				}
				if (taskData.failure_reason) {
					row.task_remark = taskData.failure_reason
				}
				if (taskData.process !== undefined) {
					row.process = taskData.process
				}
				if (taskData.download_url) {
					row.download_url = taskData.download_url
				}
			})
		} catch (error) {
			console.error('更新任务状态失败:', error)
			throw error
		}
	}

	return {
		updateSourceFileStatus,
		updateTaskStatus
	}
}

